package com.example.aidlservicedemo;

import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import androidx.annotation.NonNull;

import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 线程池工具类，用于管理不同类型的线程池，包括IO型、CPU计算型和混合型线程池。
 *
 * @author CaiJinFu
 * @since 2025/3/31
 */
public class ThreadPoolManager {

    /**
     * 设备cpu核数
     */
    private static final int CORE_POOL_SIZE = 5;

    /**
     * 线程池最大线程数
     */
    private static final int MAXIMUM_POOL_SIZE = 16;

    /**
     * 空闲线程存活时间
     */
    private static final int KEEP_ALIVE_SECONDS = 3;

    private static final Handler HANDLER = new Handler(Looper.getMainLooper());

    /**
     * io型线程设置
     */
    private static final ThreadFactory ioThreadFactory = new ThreadFactory() {
        private final AtomicInteger mCount = new AtomicInteger(1);

        @Override
        public Thread newThread(Runnable r) {
            return new Thread(r, "IO #" + mCount.getAndIncrement());
        }
    };

    /**
     * cpu计算型线程设置
     */
    private static final ThreadFactory cpuThreadFactory = new ThreadFactory() {
        private final AtomicInteger mCount = new AtomicInteger(1);

        @Override
        public Thread newThread(Runnable r) {
            return new Thread(r, "CPU #" + mCount.getAndIncrement());
        }
    };

    /**
     * io与cpu混合型
     */
    private static final ThreadFactory miscThreadFactory = new ThreadFactory() {
        private final AtomicInteger mCount = new AtomicInteger(1);

        @Override
        public Thread newThread(Runnable r) {
            return new Thread(r, "MISC #" + mCount.getAndIncrement());
        }
    };

    public static Executor ioExecutor =
        new ThreadPoolExecutor(MAXIMUM_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE_SECONDS,
            TimeUnit.SECONDS, new SynchronousQueue<Runnable>(), ioThreadFactory);

    public static Executor cpuExecutor =
        new ThreadPoolExecutor(CORE_POOL_SIZE, CORE_POOL_SIZE, KEEP_ALIVE_SECONDS, TimeUnit.SECONDS,
            new SynchronousQueue<Runnable>(), cpuThreadFactory);

    public static Executor miscExecutor = Executors.newFixedThreadPool(3, miscThreadFactory);

    /**
     * 获取 IO 线程池
     */
    public static Executor getIoExecutor() {
        return ioExecutor;
    }

    /**
     * 获取 CPU 计算型线程池
     */
    public static Executor getCpuExecutor() {
        return cpuExecutor;
    }

    /**
     * 获取混合型线程池
     */
    public static Executor getMiscExecutor() {
        return miscExecutor;
    }

    /**
     * 执行 IO 型任务
     */
    public static void ioExecute(Runnable runnable) {
        ioExecutor.execute(runnable);
    }

    /**
     * 执行带回调的任务，支持任务完成后的回调
     */
    public static void executeWithCallback(final Runnable runnable, final Runnable callback) {
        ioExecutor.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    runnable.run();
                } finally {
                    if (callback != null) {
                        callback.run(); // 执行回调
                    }
                }
            }
        });
    }

    /**
     * 优雅关闭线程池
     */
    public static void shutdownExecutor() {
        shutdownExecutor((ThreadPoolExecutor) ioExecutor);
        shutdownExecutor((ThreadPoolExecutor) cpuExecutor);
        shutdownExecutor((ThreadPoolExecutor) miscExecutor);
    }

    /**
     * 优雅关闭指定的线程池
     *
     * @param executor 需要关闭的线程池
     */
    private static void shutdownExecutor(ThreadPoolExecutor executor) {
        if (executor != null) {
            executor.shutdown(); // 防止接受新任务
            try {
                if (!executor.awaitTermination(60, TimeUnit.SECONDS)) {
                    executor.shutdownNow(); // 强制关闭
                }
            } catch (InterruptedException e) {
                executor.shutdownNow();
            }
        }
    }

    /**
     * 获取线程池状态，主要是活跃线程数和等待队列任务数
     */
    public static String getThreadPoolStatus() {
        StringBuilder status = new StringBuilder();
        status.append("IO Executor - Active Threads: ")
            .append(((ThreadPoolExecutor) ioExecutor).getActiveCount()).append("\n");
        status.append("IO Executor - Queue Size: ")
            .append(((ThreadPoolExecutor) ioExecutor).getQueue().size()).append("\n");
        status.append("CPU Executor - Active Threads: ")
            .append(((ThreadPoolExecutor) cpuExecutor).getActiveCount()).append("\n");
        status.append("CPU Executor - Queue Size: ")
            .append(((ThreadPoolExecutor) cpuExecutor).getQueue().size()).append("\n");
        status.append("MISC Executor - Active Threads: ")
            .append(((ThreadPoolExecutor) miscExecutor).getActiveCount()).append("\n");
        status.append("MISC Executor - Queue Size: ")
            .append(((ThreadPoolExecutor) miscExecutor).getQueue().size()).append("\n");
        return status.toString();
    }

    /**
     * 动态调整线程池大小（通过调整最大线程数）
     */
    public static void adjustThreadPoolSize(int maxSize) {
        ((ThreadPoolExecutor) ioExecutor).setMaximumPoolSize(maxSize);
        ((ThreadPoolExecutor) cpuExecutor).setMaximumPoolSize(maxSize);
        Log.d("ThreadPoolUtils", "Thread pool size adjusted to: " + maxSize);
    }

    /**
     * 在主线程中运行指定的Runnable对象
     *
     * @param runnable 要在主线程中执行的任务，不能为空
     */
    public static void runMainThread(@NonNull Runnable runnable) {
        HANDLER.post(runnable);
    }

    /**
     * 延迟在主线程中执行特定的Runnable任务
     *
     * @param runnable 要在主线程中执行的任务，不能为空
     * @param delayMillis 延迟执行的时间，单位为毫秒
     */
    public static void runMainThreadDelayed(@NonNull Runnable runnable, long delayMillis) {
        HANDLER.postDelayed(runnable, delayMillis);
    }

}